(function(win, doc) {
    function ms() {
        this.server = "http://172.30.1.30:8806/";
        this.setProperty = function(key, value) {
            localStorage.setItem(key, value);
        };
        this.removeProperty = function(key) {
            localStorage.removeItem(key);
        };
        this.getProperty = function(key) {
            return localStorage.getItem(key);
        };
        this.setSession = function(key, value) {
            sessionStorage.setItem(key, value);
        };
        this.getSession = function(key) {
            return sessionStorage.getItem(key) || "";
        };
        this.removeSession = function(key) {
            sessionStorage.removeItem(key);
        };
        this.clearSession = function() {
            sessionStorage.clear();
        };

        //获取cookie
        this.getCookie = function(name) {
            var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
            if (arr = document.cookie.match(reg))
                return unescape(arr[2]);
            else
                return null;
        };
        //存储cookie
        this.setCookie = function(name, value) {
            var minutes = 30;
            var exp = new Date();
            exp.setTime(exp.getTime() + minutes * 60 * 1000);
            document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/; domain=.msyd.com";
        };
        this.go = function(url) {
            window.location.href = url;
        };
        this.isWeiXin = function() {
            return /MicroMessenger/.test(navigator.userAgent);
        };
        this.isAndroid = function() {
            return /android/i.test(navigator.userAgent);
        };
        this.isIphone = function() {
            return /iphone/i.test(navigator.userAgent);
        };
        this.getHost = function() {
            var _http = window.location.protocol;
            var _hostname = window.location.hostname;
            var _port = window.location.port;
            var _pathname = window.location.pathname;
            var http = "";
            if (_port) {
                return http = _http + "//" + _hostname + ":" + _port + "/";
            }
            return http = _http + "//" + _hostname + "/";
        }

        /**
         * 获取url对象 不允许有=号的出现否则出问题
         */
        this.urlToObj = function() {
            var url = location.search; //获取url中"?"符后的字串
            var theRequest = {};
            if (url.indexOf("?") != -1) {
                var str = url.substr(1);
                strs = str.split("&");
                for (var i = 0; i < strs.length; i++) {
                    theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
                }
            }
            return theRequest;
        };
        /*
            组装url
         */
        this.urlObjToStr = function(obj) {
                var length = obj && obj.length,
                    idx = 0,
                    url = '';
                for (var key in obj) {
                    if (key != 'url' && obj[key] !== null) {
                        url += (key + '=' + encodeURIComponent(obj[key]) + '&');
                    }
                }
                return url.substring(0, url.lastIndexOf('&'));
            }
            //获取时间戳
        this.getTimeNumber = function(time) {
            var stringTime = time;
            var timestamp2 = Date.parse(new Date(stringTime));
            timestamp2 = timestamp2 / 1000;
            return timestamp2;
        }
        this.GetQueryString = function(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        }

        //初始化当前页面
        this.initAppPage = function() {
            //token 
            var token = this.GetQueryString("token");
            if (this.GetQueryString("subChannel") != "117") {
                if (token) {
                    this.setProperty("token", token);
                }
            }
            //APP操作系统
            var os = this.GetQueryString("os");
            if (os) {
                this.setSession("os", os);
            }
            //推荐码
            var recommended = this.GetQueryString("recommended");
            if (recommended) {
                this.setSession("recommended", recommended);
            }
            //渠道号
            var subChannel = this.GetQueryString("subChannel");
            if (subChannel) {
                this.setSession("subChannel", subChannel);
            }
            //设备号
            var sourceId = this.GetQueryString("sourceId");
            if (sourceId) {
                this.setSession("sourceId", sourceId);
            }
        };

        //jquery post
        this.jqpost = function(url, data, success, error) {
            data.wap = true;
            data.os = data.os || 'wap';
            data.msydChannel = 1;
            data.msydSubChannel = this.getSession("subChannel") || "144";
            data.msydEquipment = 4;
            showPostMask()
            promise.post(this.server + url,data,"form").then(function (data) {
            	hidePostMask()
            	success(data);
            },function (data) {
            	hidePostMask()
            	error&&error(data)
            })
        }
        
        this.baiduHm = function() {
            var hm = document.createElement("script");
            hm.src = "//hm.baidu.com/hm.js?3eb506bace4ba165503487954912bf59";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
        }

        this.keys = function(obj) {
            var keys = [];
            for (var pro in obj) {
                keys.push(pro);
            }
            return keys;
        }

        /* 
       	 获取values 
        */
        this.values = function(obj) {
                var values = [];
                for (var pro in obj) {
                    values.push(obj[pro]);
                }
                return values;
           }
        //获取当前的链接
        this.getSelfUrl=function(){
            return window.location.href;
        }
        this.initAppPage();
        this.baiduHm();
    }
    win.$mscomm = {};
    win.$mscomm = new ms();
    win.$mswindow = {};
    
    //jqpost网络遮罩显示
    var showPostMask = function () {
     	var dom = document.getElementById("ajax-post-mask");
    	if (!dom) {
    		var maskDom = '<div id="ajax-post-mask"><img src="/h5/app/chexian/images/loading.png" class="loading"/></div>';
    		document.querySelector("body").insertAdjacentHTML("beforeend",maskDom);
    		//阻止遮罩滚动
    		dom = document.getElementById("ajax-post-mask");
			dom.addEventListener('touchmove',function (e) {
				e.preventDefault();
			})
    	}
    	dom.style.display = 'block'
    }
    //jqpost网络遮罩隐藏
    var hidePostMask = function () {
    	document.getElementById("ajax-post-mask").style.display = 'none'
    }
	//TODO 目前只能一个提示框，不支持多个，待优化    
    $mswindow.alert = function(content,success) {
    	var dom = document.getElementById("ms-comm-alert");
    	if (!dom) {
    		var maskDom = '<div id="ms-comm-alert">'+
				'				<div class="alert-box">'+
				'					<h5>'+'温馨提醒'+'</h5>'+
				'					<div class="content">'+content+'</div>'+
				'					<div class="ms-btn-block">确定</div>'+
				'				</div>'+
				'			</div>';
    		document.querySelector("body").insertAdjacentHTML("beforeend",maskDom);
    		//阻止遮罩滚动
    		dom = document.getElementById("ms-comm-alert");
			dom.addEventListener('touchmove',function (e) {
				e.preventDefault();
			})
    	}else{
    		var maskDom = 
				'				<div class="alert-box">'+
				'					<h5>'+'温馨提醒'+'</h5>'+
				'					<div class="content">'+content+'</div>'+
				'					<div class="ms-btn-block">确定</div>'+
				'				</div>';
    		dom.innerHTML = maskDom
    	}
    	var sure = function (e) {
    		dom.style.display = 'none'
    		document.querySelector("#ms-comm-alert .ms-btn-block").removeEventListener('click',sure)
			success&&success()
    	}
    	dom.style.display = 'block'
    	document.querySelector("#ms-comm-alert .ms-btn-block").addEventListener('click',sure)
    }
    //苹果快速点击问题
    win.addEventListener('load', function() {
    	try{
    		FastClick.attach(document.body);
    	}catch(e){
    		console.log("FastClick no supper");
    	}
    }, false);
   //rem根html字体大小计算
    var docEl = doc.documentElement,   
    resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',   
    recalc = function () {   
        var clientWidth = docEl.clientWidth;   
        if (!clientWidth) return;   
        docEl.style.fontSize = clientWidth / 750 * 100 + 'px';   
    };   
    if (!doc.addEventListener) return;   
    win.addEventListener(resizeEvt, recalc, false);   
    doc.addEventListener('DOMContentLoaded', recalc, false);
})(window, document);

/*ajax请求
 * type为json，直接向后台发送json，默认为jso

 * type为form，当有嵌套时，将第二层的json转为string，将转换为a=1&b=2，这种形式，所以只支持一层json。

 * 

 */
(function(exports) {
  var Promise = function() {
	    this.callbacks = [];
	}
	
	Promise.prototype = {
	    construct: Promise,
	    resolve: function(result) {
	        this.complete("resolve", result);
    },

    reject: function(result) {
        this.complete("reject", result);
    },

    complete: function(type, result) {
    	var that = this;
        while (this.callbacks[0]) {
            this.callbacks.shift()[type](result,that);
        }
    },

    then: function(successHandler, failedHandler) {
        this.callbacks.push({
            resolve: successHandler,
            reject: failedHandler
        });

        return this;
    },
    breakp:function () {
    	this.callbacks=[];
    }
}


var status=true;

function _encode(data) {
    var payload = "";
    if (typeof data === "string") {
        payload = data;
    } else {
        var e = encodeURIComponent;
        var params = [];

        for (var k in data) {
            if (data.hasOwnProperty(k)) {
                params.push(k + '=' + data[k]);
            }
        }
        payload = params.join('&')
    }
    return payload;
}

function new_xhr() {
    var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xhr;
}


function ajax(method, url, data, type) {
    var p = new Promise();
    var xhr;
    data = data || {};
    type = type || "json";
	var payload=JSON.parse(JSON.stringify(data));
    try {
        xhr = new_xhr();
    } catch (e) {
        p.reject(false);
        return p;
    }
	
    if (method === 'GET' && payload) {
    	var encode = _encode(data);
    	if (url.indexOf("?")!=-1) {
    		if (encode) {
    			url += '&' + encode
    		}
    	}else{
    		url += '?' + _encode(data);
    	}
        payload = null;
    }else{
    	payload = JSON.stringify(payload)
    }

    xhr.open(method, url);
    var content_type = 'application/json';//'application/x-www-form-urlencoded'

	if (type == "form") {
		payload = _encode(data);
		content_type = 'application/x-www-form-urlencoded';
	}
    xhr.setRequestHeader('Content-type', content_type);
//		xhr.setRequestHeader('Content-type', 'chunked');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            var err = (!xhr.status ||
                       (xhr.status < 200 || xhr.status >= 300) &&
                       xhr.status !== 304);
            if (err) {
            	p.reject(xhr.responseText);
            } else{
            	p.resolve(JSON.parse(xhr.responseText));
            }
//              p.done(err, xhr.responseText, xhr);

        }
    };

    xhr.send(payload);
    return p;
}

var promise = {
    Promise: Promise,
    ajax: ajax,
    get: function(url, data) {
    	return ajax("GET", url, data);
	},
    post:function(url, data, type) {
        return ajax("POST", url, data, type);
    },
    breakp:function () {
    	p.callbacks=[];
    }
}
if (typeof define === 'function' && define.amd) {
    /* AMD support */
        define(function() {
            return promise;
        });
    } else {
        exports.promise = promise;
    }

})(this);